package cn.yanhu.kuwanapp.my.activity

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.adapter.OnItemClickListener
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.bean.response.RespGameListBean
import cn.yanhu.kuwanapp.bean.response.RespTaskListBean
import cn.yanhu.kuwanapp.databinding.ActivityMyTaskBinding
import cn.yanhu.kuwanapp.my.adapter.MyTaskAdapter
import cn.yanhu.kuwanapp.user.UserViewModel
import cn.yanhu.kuwanapp.utils.NavigatorHelper
import cn.yanhu.kuwanapp.utils.ext.parseState
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * 类描述：我的任务
 * @author：woochen
 * create at：2021/8/7 10:41 PM
*/
class MyTaskActivity : BaseActivity<ActivityMyTaskBinding, UserViewModel>() {

    private val mGameListDatas by lazy {
        mutableListOf<RespTaskListBean>()
    }

    private val mGameListAdapter by lazy {
        MyTaskAdapter(mGameListDatas)
    }

    override fun setContentView(): Int = R.layout.activity_my_task

    override fun initData() {
        setStatusBarStyle(false)
        initWidgets()
       requestData()
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        mViewModel.taskListInfo.observe(this, Observer { it ->
            parseState(it,{
                if (page == 1){
                    mGameListDatas.clear()
                }else{
                    if (it.isEmpty()) mBinding.refreshLayout.finishLoadMoreWithNoMoreData() else mBinding.refreshLayout.finishLoadMore()
                }
                mGameListDatas.addAll(it)
                if (mGameListDatas.isEmpty()) showEmpty()
                mGameListAdapter.notifyDataSetChanged()
            })
        })
    }

    private var page = 1
    override fun requestData() {
        mViewModel.taskList(page)
    }

    companion object {

        fun start(context: Context) {
            val intent = Intent(context, MyTaskActivity::class.java)
            context.startActivity(intent)
        }
    }

    private fun initWidgets() {
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                requestData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                refreshLayout.finishRefresh()
                requestData()
            }
        })
        mBinding.rvGame.run {
            adapter = mGameListAdapter
            mGameListAdapter.mItemClickListener = OnItemClickListener {
                val gameBean = mGameListDatas[it]
                NavigatorHelper.toCpl(mContext,gameBean.id)
//                NavigatorHelper.toCpl(mContext,gameBean.detailUrl)
            }
        }
    }
}